package blue.webserver;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;


public class MasterConn {
	private String ip_;
	private int port_;
	private SocketChannel channel_;
	
	public MasterConn(String ip, int port) throws IOException{
		ip_ = ip;
		port_ = port;
		channel_ = SocketChannel.open();
		channel_.connect(new InetSocketAddress(ip_,port_));
	}

	public String getIP() {
		return ip_;
	}

	public int getPort() {
		return port_;
	}

	public String read() throws IOException {
	    ByteBuffer recv_buf = ByteBuffer.allocate(512);
	    int recv_cnt = channel_.read(recv_buf);
	    if (recv_cnt<0) return null;
	    recv_buf.flip();
	    byte[] recv_bytes=new byte[recv_cnt];
	    recv_buf.get(recv_bytes, 0, recv_cnt);
	    
		return new String(recv_bytes,Charset.forName("UTF-8"));
	}

	public void write(String msg) throws IOException {
	    byte[] bytes = msg.getBytes( Charset.forName("UTF-8" ));
		ByteBuffer send_buf = ByteBuffer.allocate(512);
		send_buf.put(bytes);
		send_buf.flip();
		channel_.write(send_buf);
		
	}
}
